package com.czmh.etc.onlinepubsys.controller.ue;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.czmh.etc.common.core.utils.Sequence;
import com.czmh.etc.onlinepubsys.constants.ue.BusinessType;
import com.czmh.etc.onlinepubsys.entity.mingchuang.ApplyInfo;
import com.czmh.etc.onlinepubsys.entity.mingchuang.CarInfo;
import com.czmh.etc.onlinepubsys.entity.mingchuang.CurrentContext;
import com.czmh.etc.onlinepubsys.entity.mingchuang.EtcOrder;
import com.czmh.etc.onlinepubsys.json.cmg.JSONResult;
import com.czmh.etc.onlinepubsys.model.EtcUser;
import com.czmh.etc.onlinepubsys.request.ue.*;
import com.czmh.etc.onlinepubsys.response.ue.ApiResponse;
import com.czmh.etc.onlinepubsys.services.EtcOrderService;
import com.czmh.etc.onlinepubsys.services.EtcUserInfoSevice;
import com.czmh.etc.onlinepubsys.services.mingchuang.ICarInfoService;
import com.czmh.etc.onlinepubsys.services.mingchuang.ICurrentContextService;
import com.czmh.etc.onlinepubsys.services.mingchuang.IEtcApplyService;
import com.czmh.etc.onlinepubsys.services.mingchuang.IEtcOrderService;
import com.czmh.etc.onlinepubsys.utils.ImageZipUtil;
import com.czmh.etc.onlinepubsys.utils.RedisUtil;
import com.czmh.etc.onlinepubsys.utils.ue.UeHttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/{version}/api/ue/order")
@Api(tags = "4.2订单接口相关 -联合电子")
public class UeOrderController {
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ICurrentContextService currentContextService;

    @Autowired
    private IEtcApplyService etcApplyService;

    @Autowired
    private EtcOrderService etcOrderService;

    @Autowired
    private ICarInfoService carInfoService;

    @Autowired
    private IEtcOrderService orderService;

    @Autowired
    private EtcUserInfoSevice etcUserInfoSevice;

    @PostMapping("/saveAccountInfoRequest")
    @ApiOperation("4.2.1用户实名认证")
    public JSONResult saveAccountInfoRequest(@RequestBody SaveAccountInfoRequest req) {
        log.info("saveAccountInfoRequest:{}", JSON.toJSONString(req));
        String token = redisUtil.queryUeToken();
        JSONResult result = new JSONResult();
        ApiResponse r = UeHttpUtil.post(BusinessType.SAVE_ACCOUNT_INFO, JSON.toJSONString(req), token);
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                String accountId = "";
                String userno = "";
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());

                //判断object的值是json对象还是json数组，使用fastjson API
                JSONObject rsp = JSONObject.parseObject(r.getRspData());
                if (rsp.getString("object").startsWith("[")) {
                    //属性值是json数组
                    JSONArray jsonArray = JSONArray.parseArray(rsp.getString("object"));
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    accountId = jsonObject.getString(accountId);
                    userno = jsonObject.getString(userno);
                } else if (rsp.getString("object").startsWith("{")) {
                    //属性值是json对象
                    JSONObject jsonObject = JSONObject.parseObject(rsp.getString("object"));
                    accountId = jsonObject.getString("accountId");
                    userno = jsonObject.getString("userno");

                }

                //处理用户提交数据入库
                CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
                ApplyInfo applyInfo = etcApplyService.get(currentContext.getApplyId());

                //按照用户请求流程的申请ID判断更新用户申请信息还是新增用户申请信息
                if (StringUtils.isNotEmpty(currentContext.getApplyId())) {
                    if (null != applyInfo) {
                        ApplyInfo applyInfo1 = new ApplyInfo(null, req.getUserId(), "", req.getOrgan(),
                                Integer.valueOf(currentContext.getEtcUserType()), Integer.valueOf(req.getIdtype()), req.getIdnum(), "", req.getMobilephone(), "",
                                req.getIdcard_pic_url1(), req.getIdcard_pic_url2(), "", "",
                                "", null, null, null, null,
                                null, currentContext.getOrderNo(), null, null, 0, null, 0, "");
                        applyInfo1.setId(applyInfo.getId());
                        if (StringUtils.isEmpty(applyInfo.getCsUserNo())) {
                            applyInfo1.setCsUserNo(userno);
                        }
                        etcApplyService.update(applyInfo1);
                        currentContext.setApplyId(applyInfo.getId());
                    } else {
                        log.info("applyInfo is null");
                    }
                } else {
                    ApplyInfo applyInfo1 = new ApplyInfo(Sequence.getId(), req.getUserId(), "", req.getOrgan(),
                            Integer.valueOf(currentContext.getEtcUserType()), Integer.valueOf(req.getIdtype()), req.getIdnum(), req.getAgent_idnum(), req.getMobilephone(), "",
                            req.getIdcard_pic_url1(), req.getIdcard_pic_url2(), "", "",
                            "", null, null, null, null,
                            null, currentContext.getOrderNo(), null, null, 0, null, 0, "");
                    etcApplyService.save(applyInfo1);
                    currentContext.setApplyId(applyInfo1.getId());
                }
                //请求信息附加到扩展字段
                String jsonStr = currentContext.getJsonData();
                JSONObject jsonObject = JSON.parseObject(jsonStr);
                if (jsonObject == null) {
                    jsonObject = new JSONObject();
                }
                jsonObject.put("saveAccountInfoRequest", req);
                currentContext.setJsonData(jsonObject.toJSONString());
                currentContext.setState(2);
                currentContext.setCsUserNo(userno);
                currentContext.setFundAccountId(accountId);
                jsonObject.put("accountId", JSON.parseObject(r.getRspData()).getJSONObject("object").getString("accountId"));
                jsonObject.put("userno", JSON.parseObject(r.getRspData()).getJSONObject("object").getString("userno"));
                currentContext.setJsonData(jsonObject.toJSONString());
                currentContextService.update(currentContext);
                //更新地址到订单表
                String orderNo = currentContext.getOrderNo();
                EtcOrder etcOrder = etcOrderService.queryByOrderNo(orderNo);
                etcOrder.setAddress(req.getAddress());
                etcOrderService.updateById(etcOrder);
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/checkVehicle")
    @ApiOperation("4.2.2车辆办理情况查询接口（2021年7月改动）")
    public JSONResult checkVehicle(@RequestBody CheckVehicleRequest req) {
        log.info("checkVehicle:{}", JSON.toJSONString(req));
        String token = redisUtil.queryUeToken();
        JSONResult result = new JSONResult();
        ApiResponse r = UeHttpUtil.post(BusinessType.CHECK_VEHICLE, JSON.toJSONString(req), token);
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/saveCarInfo")
    @ApiOperation("4.2.3新增车辆信息")
    public JSONResult saveCarInfo(@RequestBody SaveCarInfoRequest req) {
        log.info("saveCarInfo:{}", JSON.toJSONString(req));
        String token = redisUtil.queryUeToken();
        JSONResult result = new JSONResult();
        ApiResponse r = UeHttpUtil.post(BusinessType.SAVE_CAR_INFO, JSON.toJSONString(req), token);
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());

                CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
                //根据流程汽车信息id判断是调用ETC车辆信息新增入库还是更新入库
                if (StringUtils.isEmpty(currentContext.getCarId())) {
                    CarInfo carInfo = SaveCarInfoRequest.convert(req);
                    carInfo.setId(Sequence.getId());
                    carInfoService.save(carInfo);

                    //请求信息附加到扩展字段
                    String jsonStr = currentContext.getJsonData();
                    JSONObject jsonObject = JSON.parseObject(jsonStr);
                    if (jsonObject == null) {
                        jsonObject = new JSONObject();
                    }
                    jsonObject.put("saveCarInfoRequest", req);
                    jsonObject.put("carInfoId", JSON.parseObject(r.getRspData()).getJSONObject("object").getString("carInfoId"));
                    currentContext.setJsonData(jsonObject.toJSONString());
                    //submitOrderStatus 订单提交状态，0未提交，1已提交
                    jsonObject.put("submitOrderStatus", "0");
                    //更新用户请求流程和车辆信息关联id
                    currentContext.setCarId(carInfo.getId());
                    currentContext.setState(3);
                    currentContextService.update(currentContext);
                    //更新车牌车辆颜色到订单表中
                    String orderNo = currentContext.getOrderNo();
                    EtcOrder etcOrder = etcOrderService.queryByOrderNo(orderNo);
                    etcOrder.setVehPlate(req.getVehicle_plate());
                    etcOrder.setVehColor(req.getVehicle_color() != null ? Integer.valueOf(req.getVehicle_color()) : null);
                    etcOrderService.updateById(etcOrder);
                } else {
                    result.setCode(JSONResult.FAIL);
                    result.setMessage("车辆信息已存在,请不要重复提交！");
                }
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/productDetail")
    @ApiOperation("4.2.4产品推荐查询")
    public JSONResult productDetail(@RequestBody ProductDetailRequest req) {
        log.info("productDetail:{}", JSON.toJSONString(req));
        String token = redisUtil.queryUeToken();
        JSONResult result = new JSONResult();
        ApiResponse r = UeHttpUtil.post(BusinessType.PRODUCT_DETAIL, JSON.toJSONString(req), token);
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/payChannel")
    @ApiOperation("4.2.5签约渠道查询")
    public JSONResult payChannel(@RequestBody PayChannelRequest req) {
        log.info("payChannel:{}", JSON.toJSONString(req));
        String token = redisUtil.queryUeToken();
        JSONResult result = new JSONResult();
        ApiResponse r = UeHttpUtil.post(BusinessType.PAY_CHANNEL, JSON.toJSONString(req), token);
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/submitOrder")
    @ApiOperation("4.2.6订单提交")
    public JSONResult submitOrder(@RequestBody SubmitOrderRequest req) {
        log.info("submitOrder:{}", JSON.toJSONString(req));
        String token = redisUtil.queryUeToken();
        JSONResult result = new JSONResult();
        ApiResponse r = UeHttpUtil.post(BusinessType.SUBMIT_ORDER, JSON.toJSONString(req), token);
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());

                CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
                //请求信息附加到扩展字段
                String jsonStr = currentContext.getJsonData();
                JSONObject jsonObject = JSON.parseObject(jsonStr);
                if (jsonObject == null) {
                    jsonObject = new JSONObject();
                }
                jsonObject.put("SubmitOrderRequest", req);

                //submitOrderStatus 订单提交状态，0未提交，1已提交
                jsonObject.put("order_id", JSON.parseObject(r.getRspData()).getJSONObject("object").getString("order_id"));
                jsonObject.put("submitOrderStatus", "1");
                currentContext.setJsonData(jsonObject.toJSONString());
                currentContextService.update(currentContext);
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/appletUpdateOrderUser")
    @ApiOperation("4.2.7 订单修改接口（修改申办人资料）")
    public JSONResult appletUpdateOrderUser(@RequestBody AppletUpdateOrderUserRequest req) {
        log.info("appletUpdateOrderUser:{}", JSON.toJSONString(req));
        String token = redisUtil.queryUeToken();
        JSONResult result = new JSONResult();
        ApiResponse r = UeHttpUtil.post(BusinessType.APPLET_UPDATE_ORDER_USER, JSON.toJSONString(req), token);
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                String accountId = "";
                String userno = "";
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());
/*

                //判断object的值是json对象还是json数组，使用fastjson API
                JSONObject rsp = JSONObject.parseObject(r.getRspData());
                if (rsp.getString("object").startsWith("[")) {
                    //属性值是json数组
                    JSONArray jsonArray = JSONArray.parseArray(rsp.getString("object"));
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    accountId = jsonObject.getString(accountId);
                    userno = jsonObject.getString(userno);
                } else if (rsp.getString("object").startsWith("{")) {
                    //属性值是json对象
                    JSONObject jsonObject = JSONObject.parseObject(rsp.getString("object"));
                    accountId = jsonObject.getString("accountId");
                    userno = jsonObject.getString("userno");

                }
*/

                //处理用户提交数据入库
                CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
                ApplyInfo applyInfo = etcApplyService.get(currentContext.getApplyId());

                //按照用户请求流程的申请ID判断更新用户申请信息还是新增用户申请信息
                if (StringUtils.isNotEmpty(currentContext.getApplyId())) {
                    if (null != applyInfo) {
                        applyInfo.setPhone(req.getMobilephone());
                        applyInfo.setAgentFrontImg(req.getOss_idcard_pic_url1());
                        applyInfo.setAgentBackImg(req.getOss_idcard_pic_url2());
                        etcApplyService.update(applyInfo);
                        currentContext.setApplyId(applyInfo.getId());
                    } else {
                        result.setCode(JSONResult.FAIL);
                        result.setMessage("用户申请信息不存在");
                    }
                } else {
                    result.setCode(JSONResult.FAIL);
                    result.setMessage("用户申请信息不存在");
                }
                //请求信息附加到扩展字段
                String jsonStr = currentContext.getJsonData();
                JSONObject jsonObject = JSON.parseObject(jsonStr);
                if (jsonObject == null) {
                    jsonObject = new JSONObject();
                }
                String saveAccountInfoRequestStr = jsonObject.getString("saveAccountInfoRequest");
                JSONObject saveAccountInfoRequest = JSON.parseObject(saveAccountInfoRequestStr);
                if(saveAccountInfoRequest != null){
                    String applyExtInfoStr = saveAccountInfoRequest.getString("applyExtInfo");
                    JSONObject applyExtInfo = JSON.parseObject(applyExtInfoStr);
                    if(applyExtInfo != null){
                        applyExtInfo.put("agentFrontImgUrl", req.getOss_idcard_pic_url1());
                        applyExtInfo.put("agentBackImgUrl", req.getOss_idcard_pic_url2());
                    }
                    saveAccountInfoRequest.put("applyExtInfo", applyExtInfo);
                    saveAccountInfoRequest.put("idcard_pic_url1", req.getIdcard_pic_url1());
                    saveAccountInfoRequest.put("idcard_pic_url2", req.getIdcard_pic_url2());
                }
                jsonObject.put("saveAccountInfoRequest", saveAccountInfoRequest);
                jsonObject.put("appletUpdateOrderUser", req);
                currentContext.setJsonData(jsonObject.toJSONString());
                //currentContext.setState(2);
                currentContext.setCsUserNo(userno);
                currentContext.setFundAccountId(accountId);
                currentContextService.update(currentContext);
                //更新地址到订单表
                String orderNo = currentContext.getOrderNo();
                EtcOrder etcOrder = etcOrderService.queryByOrderNo(orderNo);
                etcOrder.setAddress(req.getUser_info_address());
                etcOrderService.updateById(etcOrder);
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/updateVehicle")
    @ApiOperation("4.2.8 订单修改接口（修改车辆信息）")
    public JSONResult updateVehicle(@RequestBody UpdateVehicleRequest req) {
        log.info("updateVehicle:{}", JSON.toJSONString(req));
        String token = redisUtil.queryUeToken();
        JSONResult result = new JSONResult();
        ApiResponse r = UeHttpUtil.post(BusinessType.UPDATE_VEHICLE, JSON.toJSONString(req), token);
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());

                //处理用户提交数据入库
                CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
                ApplyInfo applyInfo = etcApplyService.get(currentContext.getApplyId());

                //按照用户请求流程的申请ID判断更新用户申请信息还是新增用户申请信息
                if (StringUtils.isNotEmpty(currentContext.getApplyId())) {
                    if (null != applyInfo) {
                        applyInfo.setVehCertFrontImg(req.getOss_veh_license_pic_url1());
                        applyInfo.setVehCertbackImg(req.getOss_veh_license_pic_url2());
                        etcApplyService.update(applyInfo);
                        currentContext.setApplyId(applyInfo.getId());
                    } else {
                        result.setCode(JSONResult.FAIL);
                        result.setMessage("用户申请信息不存在");
                    }
                } else {
                    result.setCode(JSONResult.FAIL);
                    result.setMessage("用户申请信息不存在");
                }
                //请求信息附加到扩展字段
                String jsonStr = currentContext.getJsonData();
                JSONObject jsonObject = JSON.parseObject(jsonStr);
                if (jsonObject == null) {
                    jsonObject = new JSONObject();
                }
                jsonObject.put("updateVehicleRequest", req);
                currentContext.setJsonData(jsonObject.toJSONString());
                String saveCarInfoRequestStr = jsonObject.getString("saveCarInfoRequest");
                JSONObject saveCarInfoRequest = JSON.parseObject(saveCarInfoRequestStr);
                if(saveCarInfoRequest != null){
                    String applyExtInfoStr = saveCarInfoRequest.getString("applyExtInfo");
                    JSONObject applyExtInfo = JSON.parseObject(applyExtInfoStr);
                    if(applyExtInfo != null){
                        applyExtInfo.put("vehCertFrontImgUrl", req.getOss_veh_license_pic_url1());
                        applyExtInfo.put("vehCertBackImgUrl", req.getOss_veh_license_pic_url2());
                    }
                    saveCarInfoRequest.put("applyExtInfo", applyExtInfo);
                    saveCarInfoRequest.put("veh_license_pic_url1", req.getVeh_license_pic_url1());
                    saveCarInfoRequest.put("veh_license_pic_url2", req.getVeh_license_pic_url2());
                }
                jsonObject.put("saveCarInfoRequest", saveCarInfoRequest);
                currentContext.setJsonData(jsonObject.toJSONString());
                currentContextService.update(currentContext);
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/cancelOrder")
    @ApiOperation("4.2.10 取消订单")
    public JSONResult cancelOrder(@RequestBody CancelOrderRequest req) {
        log.info("cancelOrder:{}", JSON.toJSONString(req));
        String token = redisUtil.queryUeToken();
        JSONResult result = new JSONResult();
        ApiResponse r = UeHttpUtil.post(BusinessType.CANCEL_ORDER, JSON.toJSONString(req), token);
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());
                CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
                currentContext.setState(6);
                currentContext.setDeleteFlag(1);
                currentContextService.update(currentContext);
                EtcOrder etcOrder = etcOrderService.queryByOrderNo(currentContext.getOrderNo());
                EtcUser etcUser = etcUserInfoSevice.queryUserInfo(currentContext.getUserId());
                log.info("联合电服取消订单同步逻辑删流程单数据:{}", JSON.toJSONString(currentContext));
                log.info("联合电服取消订单同步物理删除订单数据:{}", JSON.toJSONString(etcOrder));
                log.info("联合电服取消订单同步重置用户数据:{}", JSON.toJSONString(etcUser));
                etcOrder.setPayState(3);
                etcOrder.setBody(etcOrder.getBody() + "@" + currentContext.getId());
                orderService.updateByObject(etcOrder);
                etcUser.setUser_loginname("");
                etcUser.setUser_phone("");
                etcUserInfoSevice.updateUser(etcUser);
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }


    @PostMapping("/getOrderPayStatus")
    @ApiOperation("4.2.12 订单状态查询接口（根据订单")
    public JSONResult getOrderPayStatus(@RequestBody GetOrderPayStatusRequest req) {
        log.info("getOrderPayStatus:{}", JSON.toJSONString(req));
        String token = redisUtil.queryUeToken();
        JSONResult result = new JSONResult();
        ApiResponse r = UeHttpUtil.post(BusinessType.GET_ORDER_PAY_STATUS, JSON.toJSONString(req), token);
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/queryOrderByVehicle")
    @ApiOperation("4.2.13订单状态查询接口（根据车牌查）")
    public JSONResult queryOrderByVehicle(@RequestBody QueryOrderByVehicleRequest req) {
        log.info("queryOrderByVehicle:{}", JSON.toJSONString(req));
        String token = redisUtil.queryUeToken();
        JSONResult result = new JSONResult();
        ApiResponse r = UeHttpUtil.post(BusinessType.QUERY_ORDER_BY_VEHICLE, JSON.toJSONString(req), token);
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/queryOrderListByAppKey")
    @ApiOperation("4.2.14.1订单列表")
    public JSONResult queryOrderListByAppKey(@RequestBody QueryOrderListByAppKeyRequest req) {
        log.info("queryOrderListByAppKey:{}", JSON.toJSONString(req));
        String token = redisUtil.queryUeToken();
        JSONResult result = new JSONResult();
        ApiResponse r = UeHttpUtil.post(BusinessType.QUERY_ORDER_LIST_BY_APPKEY, JSON.toJSONString(req), token);
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/uploadPhoto")
    @ApiOperation("4.2.14.4图片上传")
    public JSONResult uploadPhoto(@RequestBody UploadPhotoRequest req) {
        //log.info("uploadPhoto:{}", JSON.toJSONString(req));
        String token = redisUtil.queryUeToken();
        JSONResult result = new JSONResult();
        ApiResponse r = UeHttpUtil.post(BusinessType.UPLOAD_PHOTO, JSON.toJSONString(req), token);
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/uploadPhotoSrc")
    @ApiOperation("4.2.14.4图片上传-根据源文件对应的base64进行压缩")
    public JSONResult uploadPhotoSrc(@RequestBody UploadPhotoRequest req) {
        //log.info("uploadPhotoSrc:{}", JSON.toJSONString(req));
        String token = redisUtil.queryUeToken();
        JSONResult result = new JSONResult();
        if(StringUtils.isNotEmpty(req.getAgentIdCardPicBack())){
            req.setAgentIdCardPicBack(ImageZipUtil.handleAndReduceBase64(req.getAgentIdCardPicBack()));
        }
        if(StringUtils.isNotEmpty(req.getAgentIdCardPicFront())){
            req.setAgentIdCardPicFront(ImageZipUtil.handleAndReduceBase64(req.getAgentIdCardPicFront()));
        }
        if(StringUtils.isNotEmpty(req.getAuthPic())){
            req.setAuthPic(ImageZipUtil.handleAndReduceBase64(req.getAuthPic()));
        }
        if(StringUtils.isNotEmpty(req.getCardPic1())){
            req.setCardPic1(ImageZipUtil.handleAndReduceBase64(req.getCardPic1()));
        }
        if(StringUtils.isNotEmpty(req.getCardPic2())){
            req.setCardPic2(ImageZipUtil.handleAndReduceBase64(req.getCardPic2()));
        }
        if(StringUtils.isNotEmpty(req.getCompanyIdCardPic())){
            req.setCompanyIdCardPic(ImageZipUtil.handleAndReduceBase64(req.getCompanyIdCardPic()));
        }
        if(StringUtils.isNotEmpty(req.getIdCardPicBack())){
            req.setIdCardPicBack(ImageZipUtil.handleAndReduceBase64(req.getIdCardPicBack()));
        }
        if(StringUtils.isNotEmpty(req.getIdCardPicFront())){
            req.setIdCardPicFront(ImageZipUtil.handleAndReduceBase64(req.getIdCardPicFront()));
        }
        if(StringUtils.isNotEmpty(req.getInvoicePic())){
            req.setInvoicePic(ImageZipUtil.handleAndReduceBase64(req.getInvoicePic()));
        }
        if(StringUtils.isNotEmpty(req.getOwnerPicBack())){
            req.setOwnerPicBack(ImageZipUtil.handleAndReduceBase64(req.getOwnerPicBack()));
        }
        if(StringUtils.isNotEmpty(req.getOwnerPicFront())){
            req.setOwnerPicFront(ImageZipUtil.handleAndReduceBase64(req.getOwnerPicFront()));
        }
        if(StringUtils.isNotEmpty(req.getRoadTransportPic())){
            req.setRoadTransportPic(ImageZipUtil.handleAndReduceBase64(req.getRoadTransportPic()));
        }
        if(StringUtils.isNotEmpty(req.getSignPic())){
            req.setSignPic(ImageZipUtil.handleAndReduceBase64(req.getSignPic()));
        }
        if(StringUtils.isNotEmpty(req.getVehicleBodyPic())){
            req.setVehicleBodyPic(ImageZipUtil.handleAndReduceBase64(req.getVehicleBodyPic()));
        }
        if(StringUtils.isNotEmpty(req.getVehicleGrantPic())){
            req.setVehicleGrantPic(ImageZipUtil.handleAndReduceBase64(req.getVehicleGrantPic()));
        }
        if(StringUtils.isNotEmpty(req.getVehLicensePicBack())){
            req.setVehLicensePicBack(ImageZipUtil.handleAndReduceBase64(req.getVehLicensePicBack()));
        }
        if(StringUtils.isNotEmpty(req.getVehLicensePicFront())){
            req.setVehLicensePicFront(ImageZipUtil.handleAndReduceBase64(req.getVehLicensePicFront()));
        }
        ApiResponse r = UeHttpUtil.post(BusinessType.UPLOAD_PHOTO, JSON.toJSONString(req), token);
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    /**
     * 根据产品编码查询和重置数据信息，物理删除订单列表和流程数据，同时把用户列表的手机号码设置为空
     *
     * @return
     */
    @ApiOperation(value = "resetData", notes = "根据产品编码查询和重置数据信息")
    @GetMapping("/resetData")
    public JSONResult resetData(@ApiParam(value = "产品编码", required = true) @RequestParam(value = "productSn", required = true) String productSn,
                                        @ApiParam(value = "操作类型：不传默认为查询，1为查询 2为重置", required = true) @RequestParam(value = "type", required = true) Integer type,
                                        @ApiParam(value = "渠道：4为联合电子", required = true) @RequestParam(value = "channel", required = true) Integer channel,
                                         @ApiParam(value = "接口秘钥", required = true) @RequestParam(value = "pwd", required = true) String pwd) {
        JSONResult result = new JSONResult();
        Object object = redisUtil.get("menuPass");
        if(object == null || !object.toString().equalsIgnoreCase(pwd)){
            result.setCode(com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.FAIL);
            result.setMessage("接口秘钥配置不能为空，请联系管理员！");
            return result;
        }
        if(StringUtils.isEmpty(productSn)){
            result.setCode(com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.FAIL);
            result.setMessage("产品编码不能为空");
            return result;
        }
        //判断产品编码对应的订单是否存在
        EtcOrder etcOrder = orderService.getByProductSn(productSn);
        if (etcOrder == null) {
            result.setCode(com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.FAIL);
            result.setMessage("产品编码对应订单不存在");
            return result;
        }
        if(type == null || type == 1){
            result.setCode(com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.SUCCESS);
            result.setRspData(JSON.toJSONString(etcOrder));
            return result;
        }
        //判断产品编码对应的用户流程是否存在
        CurrentContext currentContext = currentContextService.getByOrderNo(etcOrder.getOrderNo());
        if (currentContext == null) {
            result.setCode(com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.FAIL);
            result.setMessage("产品编码对应用户流程不存在");
            return result;
        }
        String jsonStr = currentContext.getJsonData();
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        if(type == 2){
            if (etcOrder.getType() != channel) {
                result.setCode(com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.FAIL);
                result.setMessage("产品编码对应渠道不符合:" + etcOrder.getType());
                return result;
            }
            if (jsonObject != null) {
                String  submitOrderStatus = jsonObject.getString("submitOrderStatus");
                String order_id = jsonObject.getString("order_id");
                if(submitOrderStatus != null && order_id != null && submitOrderStatus.equalsIgnoreCase("1")){
                    //取消联合电子订单之前先查询订单状态，如果是激活订单则不能取消
                    //查询已提交订单状态
                    String token = redisUtil.queryUeToken();
                    QueryOrderByVehicleRequest request = new QueryOrderByVehicleRequest();
                    CarInfo etcCarInfo = carInfoService.get(currentContext.getCarId());
                    if (etcCarInfo != null) {
                        request.setVehicleColor(String.valueOf(etcCarInfo.getVehColor()));
                        request.setVehiclePlate(etcCarInfo.getVehPlate());
                    }
                    ApiResponse r = UeHttpUtil.postNoLog(BusinessType.QUERY_ORDER_BY_VEHICLE, JSON.toJSONString(request), token);
                    if (r != null && r.getSuccess()) {
                        if (r.getSuccess()) {
                            //查看是否激活
                            if (r.getRspData() != null) {
                                JSONObject rsp = JSON.parseObject(r.getRspData());
                                JSONObject o = JSON.parseObject(rsp.getString("object"));
                                if (o != null && o.getString("object") != null) {
                                    JSONArray jsonArray = JSON.parseArray(o.getString("object"));
                                    if (jsonArray != null && jsonArray.size() > 0) {
                                        JSONObject jObject = (JSONObject) jsonArray.get(0);
                                        if (jObject.getString("order_status") != null
                                                && !jObject.getString("order_status").equalsIgnoreCase("5")
                                                && !jObject.getString("order_status").equalsIgnoreCase("4")) {
                                            CancelOrderRequest req = new CancelOrderRequest();
                                            req.setBind_tel(etcOrder.getPhone());
                                            req.setOrder_id(order_id);
                                            req.setCancel_reason("不想要了");
                                            log.info("根据产品编码查询和重置数据信息-resetData:{}", JSON.toJSONString(req));
                                            ApiResponse response = UeHttpUtil.post(BusinessType.CANCEL_ORDER, JSON.toJSONString(req), token);
                                            if (response != null && response.getSuccess()) {
                                                if (response.getSuccess()) {
                                                    EtcUser etcUser = etcUserInfoSevice.queryUserInfo(currentContext.getUserId());
                                                    result.setRspData(r.getRspData());
                                                    result.setMessage(r.getMsg());
                                                    jsonObject.put("delete_status", 1);
                                                    currentContext.setJsonData(jsonObject.toJSONString());
                                                    currentContextService.update(currentContext);
                                                    log.info("根据产品编码查询和重置数据信息-resetData-currentContext:{}",JSON.toJSONString(currentContext));
                                                    log.info("根据产品编码查询和重置数据信息-resetData-etcOrder:{}",JSON.toJSONString(etcOrder));
                                                    log.info("根据产品编码查询和重置数据信息-resetData-etcUser:{}",JSON.toJSONString(etcUser));
                                                    currentContextService.delete(currentContext.getId());
                                                    etcOrder.setPayState(3);
                                                    etcOrder.setBody(etcOrder.getBody() + "@" + currentContext.getId());
                                                    orderService.updateByObject(etcOrder);
                                                    etcUser.setUser_loginname("");
                                                    etcUser.setUser_phone("");
                                                    etcUserInfoSevice.updateUser(etcUser);
                                                }
                                            } else {
                                                result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
                                                result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
                                            }
                                        }else {
                                            result.setCode(com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.FAIL);
                                            result.setMessage("联合电服订单已激活无法取消和重置");
                                            return result;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return result;
                }else{
                    EtcUser etcUser = etcUserInfoSevice.queryUserInfo(currentContext.getUserId());
                    jsonObject.put("delete_status", 1);
                    currentContext.setJsonData(jsonObject.toJSONString());
                    currentContextService.update(currentContext);
                    log.info("根据产品编码查询和重置数据信息-resetData-currentContext:{}",JSON.toJSONString(currentContext));
                    log.info("根据产品编码查询和重置数据信息-resetData-etcOrder:{}",JSON.toJSONString(etcOrder));
                    log.info("根据产品编码查询和重置数据信息-resetData-etcUser:{}",JSON.toJSONString(etcUser));
                    currentContextService.delete(currentContext.getId());
                    etcOrder.setPayState(3);
                    etcOrder.setBody(etcOrder.getBody() + "@" + currentContext.getId());
                    orderService.updateByObject(etcOrder);
                    etcUser.setUser_loginname("");
                    etcUser.setUser_phone("");
                    etcUserInfoSevice.updateUser(etcUser);
                    result.setMessage("数据重置成功");
                }
            }else{
                result.setCode(com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.FAIL);
                result.setMessage("用户流程数据为空无法操作");
                return result;
            }
        }
        if(channel != 4){
            EtcUser etcUser = etcUserInfoSevice.queryUserInfo(currentContext.getUserId());
            jsonObject.put("delete_status", 1);
            currentContext.setJsonData(jsonObject.toJSONString());
            currentContextService.update(currentContext);
            log.info("根据产品编码查询和重置数据信息-resetData-currentContext:{}",JSON.toJSONString(currentContext));
            log.info("根据产品编码查询和重置数据信息-resetData-etcOrder:{}",JSON.toJSONString(etcOrder));
            log.info("根据产品编码查询和重置数据信息-resetData-etcUser:{}",JSON.toJSONString(etcUser));
            currentContextService.delete(currentContext.getId());
            etcOrder.setPayState(3);
            etcOrder.setBody(etcOrder.getBody() + "@" + currentContext.getId());
            orderService.updateByObject(etcOrder);
            etcUser.setUser_loginname("");
            etcUser.setUser_phone("");
            etcUserInfoSevice.updateUser(etcUser);
            result.setMessage("数据重置成功");
        }
        return result;
    }
}
